package com.emar.spring.dao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import com.emar.spring.common.util.StringUtil;
import com.emar.spring.dto.ParamsDTO;

/**
 * jdbc操作的公共基类
 */
@Repository
public class BaseDAO {
	private Log log = LogFactory.getLog(BaseDAO.class);
	private JdbcTemplate jdbcTemplate;

	protected String getWhereSql(ParamsDTO dto) {
		StringBuffer sb = new StringBuffer();
//		Class cla = ParamsDTO.class;
//		Method methods[] = cla.getMethods(); // 反射机制，获取公共方法
//		Field flelds[] = cla.getDeclaredFields(); // 反射，获取声明的变量
//
//		for (Method m : methods) {
//			Class<?> returnType = m.getReturnType();
//			Class<?> parameterTypes[] = m.getParameterTypes();	//获取方法中传入的参数
//			
//			StringBuffer sbParams = new StringBuffer();
//			if(parameterTypes != null || parameterTypes.length == 1){
//				for (Class<?> clas : parameterTypes) {
//					sbParams.append(clas.getName());
//				}
//			}
//			
//			try {
//				                                                                                                                                                                                                                                                                                                       
//				if ("int".equals(returnType.getName()) || "java.lang.Integer".equals(returnType.getName())) {
//					if (StringUtil.isNotZero((Integer) m.invoke(dto))) {
//						sb.append( " and ");
//						sb.append(sbParams.toString());
//						sb.append( " = '");
//						sb.append(m.invoke(dto));
//						sb.append( "'");
//					}
//
//				} else if ("String".equals(returnType.getName()) || "java.lang.String".equals(returnType.getName())) {
//					if(StringUtil.isNotEmpty((String) m.invoke(dto))){
//						sb.append( " and ");
//						sb.append(sbParams.toString());
//						sb.append( " = '");
//						sb.append(m.invoke(dto));
//						sb.append( "'");
//					}
//				}
//			} catch (IllegalArgumentException e) {
//				e.printStackTrace();
//			} catch (IllegalAccessException e) {
//				e.printStackTrace();
//			} catch (InvocationTargetException e) {
//				e.printStackTrace();
//			}
////			int temp = m.getModifiers();
////			System.out.println(Modifier.toString(temp) + " ");
////			System.out.println(returnType.getName() + "  ");
////			System.out.println(m.getName() + " ");
//		}
		if (StringUtil.isNotZero(dto.getProjectId())) {
			sb.append(" and p.`ProjectID` = " + dto.getProjectId());
		}
		if (StringUtil.isNotZero(dto.getSystemId())) {
			sb.append(" and s.`SystemId` = " + dto.getSystemId());
		}
		if (StringUtil.isNotEmpty(dto.getProjectName())) {
			sb.append(" and p.`ProjectName` like '%" + dto.getProjectName()
					+ "%'");
		}
		if (StringUtil.isNotEmpty(dto.getProjectType())) {
			sb.append(" and p.`ProjectType` = '" + dto.getProjectType() + "'");
		}
		if (StringUtil.isNotEmpty(dto.getObjType1())) {
			sb.append(" and r.`ObjType1` = '" + dto.getObjType1() + "'");
		}
		if (StringUtil.isNotEmpty(dto.getProjectStatus())) {
			sb.append(" and p.`ProjectStatus` = '" + dto.getProjectStatus()
					+ "'");
		}
		if (StringUtil.isNotEmpty(dto.getCommissionCorpName())) {
			sb.append(" and p.`CommissionCorpName` like '%"
					+ dto.getCommissionCorpName() + "%'");
		}
		if (StringUtil.isNotEmpty(dto.getRecordJudge())) {
			sb.append(" and r.`RecordJudge` = '" + dto.getRecordJudge() + "'");
		}
		if (StringUtil.isNotEmpty(dto.getIsValid())) {
			sb.append(" and r.`isValid` = '" + dto.getIsValid() + "'");
		}
		if (StringUtil.isNotEmpty(dto.getCommissionCorpLinkName())) {
			sb.append(" and p.`CommissionCorpLinkName` = '"
					+ dto.getCommissionCorpLinkName() + "'");
		}
		if (StringUtil.isNotEmpty(dto.getSystemName())) {
			sb.append(" and s.`SystemName` like '%" + dto.getSystemName()
					+ "%'");
		}
		if (StringUtil.isNotZero(dto.getSecurityLevelCode())) {
			sb.append(" and s.`SecurityLevelCode` = '"
					+ dto.getSecurityLevelCode() + "'");
		}
		return sb.toString().replaceFirst("and", "where");
	}

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	/**
	 * 更新操作
	 * 
	 * @param namedSql
	 * @param javaBean
	 * @return
	 */
	protected int update(String namedSql, Object javaBean) {
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(
				javaBean);
		return this.jdbcTemplate.update(namedSql, paramSource);
	}

	/**
	 * 批量更新
	 * 
	 * @param sql
	 * @param paramValue
	 * @return
	 */
	protected int commonUpdate(String sql, Object... paramValue) {
		return this.jdbcTemplate.update(sql, paramValue);
	}

	/**
	 * 获取count计数
	 * 
	 * @param sql
	 * @return
	 */
	protected int getCount(String sql) {
		return this.jdbcTemplate.queryForObject(sql, Integer.class);
	}

	/**
	 * 获取一个bean实体
	 * 
	 * @param sql
	 * @param returnType
	 * @return
	 */
	protected <T> T getJavaBean(String sql, Class<T> returnType) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(returnType);
		try {
			return this.jdbcTemplate.queryForObject(sql, rowMapper);
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 获取list
	 * 
	 * @param sql
	 * @param returnType
	 * @return
	 */
	protected <T> List<T> getList(String sql, Class<T> returnType) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(returnType);
		log.info(sql);
		return this.jdbcTemplate.query(sql, rowMapper);
	}

	protected <T> List<T> getList(String sql, Class<T> returnType,
			Object... paramValue) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(returnType);
		return this.jdbcTemplate.query(sql, rowMapper, paramValue);
	}

	/**
	 * 分页获取list
	 * 
	 * @param sql
	 * @param returnType
	 * @return
	 */
	protected <T> List<T> getPageList(String querySQL, Class<T> returnType,
			int pageNumber, int pageSize) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(returnType);
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select * from ( ");
		sqlBuffer.append(querySQL);
		sqlBuffer.append(" ) as t limit " + pageNumber + "," + pageSize);
		log.info(sqlBuffer.toString());
		return this.jdbcTemplate.query(sqlBuffer.toString(), rowMapper);
	}

}
